import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class SuperMarket {


    /**
     * 超市名称
     */
    private String name;

    /**
     * 出售水果的列表
     */
    private Map<String,Fruit> fruitMap = new HashMap<String,Fruit>();

    /**
     * 超市折扣达到的价格
     */
    private Double srcPrice;

    /**
     * 超市折扣减去的价格
     */
    private Double minusPrice;

    /**
     * 上架水果，PS：由于此处未提及水果库存数量，故没有设置库存属性字段，未作库存设置
     * @param fruit
     */
    public void putFruit(Fruit fruit) {
        String name = fruit.getName();
        fruitMap.put(name, fruit);
    }

    /**
     * 下架水果，PS：由于此处未提及水果库存数量，故没有设置库存属性字段，未作库存扣减
     */
    public void pullFruit(Fruit fruit) {
        fruitMap.remove(fruit.getName());
    }

    /**
     * 根据名称获取水果
     */
    public Fruit getFruit(String name) {
        Fruit fruit = fruitMap.get(name);
        if(fruit == null) {
            throw new RuntimeException("购买失败，超市未上架该名称的水果：" + name);
        }
        return fruitMap.get(name);
    }

    /**
     * 购买水果
     */
    public void buyFruit(Customer customer,String fruit,int quantity) {
        //定义单项订单
        FuitItemOrder fuitItemOrder = new FuitItemOrder();
        //设置购买数量
        fuitItemOrder.setQuantity(quantity);
        //设置购买的水果。PS：由于此处未提及水果库存数量，故没有设置库存属性字段，未作库存扣减
        fuitItemOrder.setFruit(this.getFruit(fruit));
        //添加到总订单
        Order order = customer.getOrder();
        order.getFuitItemOrderList().add(fuitItemOrder);
    }

    /**
     * 计算客户订单总价
     * @param customerA
     * @return
     */
    public Double calcTotal(Customer customer) {
        return customer.getOrder().calculateTotal();
    }

    public SuperMarket(String name) {
        this.name = name;
    }

    public void outputOrder(Customer customer) {
        String result = String.format("顾客【%s】在【%s】购买水果的总价格是【%s】",customer.getName(),this.name,calculateTotal(customer));
        System.out.println(result);
    }

    public Double calculateTotal(Customer customer){

        Double total = customer.getOrder().calculateTotal();
        //如果设置超市折扣，则计算折扣
        if(srcPrice != null && minusPrice != null) {
            double v = Math.floor(total / getSrcPrice());
            total = total - (v * getMinusPrice());
        }

        return parseNum(total);

    }

    /**
     * 保留两位小数
     * @return
     */
    public Double parseNum(Double num){
        DecimalFormat df = new DecimalFormat("#.##");
        String result = df.format(num);
        return Double.parseDouble(result);
    }

    public Double getSrcPrice() {
        return srcPrice;
    }

    public void setSrcPrice(Double srcPrice) {
        this.srcPrice = srcPrice;
    }

    public Double getMinusPrice() {
        return minusPrice;
    }

    public void setMinusPrice(Double minusPrice) {
        this.minusPrice = minusPrice;
    }
}
